import logging
import os
import time

from utils.file_util import createPath, TYPE_DIR
from utils.time_util import fmt_d, YYYYMMDD2

logdir = "./log"


class Logger:
    def __init__(self):
        createPath(logdir, TYPE_DIR)
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(level=logging.INFO)
        self.logger.addHandler(self.loghandler())
        self.logger.addHandler(self.logconsole())

    def loghandler(self):
        handler = logging.FileHandler(self.getfilepath())
        handler.setLevel(logging.INFO)
        handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
        return handler

    def logconsole(self):
        console = logging.StreamHandler()
        console.setLevel(logging.INFO)
        return console

    def getfilepath(self):
        return logdir + "/pyspider_log_" + fmt_d(None, YYYYMMDD2) + ".log"

    def info(self, msg):
        self.createpath()
        self.logger.info(msg)

    def debug(self, msg):
        self.createpath()
        self.logger.debug(msg)

    def warning(self, msg):
        self.createpath()
        self.logger.warning(msg)

    def error(self, msg):
        self.createpath()
        self.logger.error(msg)

    def wirteline(self):
        self.createpath()
        self.logger.info("-------------------\n")

    def createpath(self):
        createPath(logdir, TYPE_DIR)
        if os.path.exists(logdir+"/pyspider_log_" + fmt_d(None, YYYYMMDD2) + ".log") is False:
            for handler in self.logger.handlers:
                self.logger.removeHandler(handler)
            self.logger.addHandler(self.loghandler())
            self.logger.addHandler(self.logconsole())

loger = Logger()

if __name__ == '__main__':
    while True:
        loger.info("hello\nwosas\nasas\ndsfdss")
        time.sleep(10)
